﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Web.Core;
using System.Collections;
using System.Collections.Specialized;

namespace Yuanlin.Business
{
    public class CompanyFisheryEditControl : YuanlinUserControl,
        IReplyConverter<CompanyFisheryReply, GetOperation>
    {
        protected ValuedTextBox titleValuedTextBox;//名称
        protected ValuedTextBox aliasValuedTextBox;//别名
        protected ValuedTextBox pinNameTitleValuedTextBox;//品种
        protected RadioButtonList categoryRadioButtonList;//植物分类
        protected CheckBoxList applicationCategoryCheckBoxList;
        protected ValuedTextBox numberValuedTextBox;//数量
        protected ValuedTextBox priceValuedTextBox;//价格
        protected CheckBoxList aquacultureMethodCheckBoxList;//养殖方式
        protected CheckBoxList aquacultureAttributeCheckBoxList;//养殖属性
        protected ValuedTextBox registerTrademarkValuedTextBox;//注册商标
        protected ValuedCheckBox productPriceFromFaceCheckBox;//是否面议
        protected RadioButtonList expiredInfoRadioButtonList;//信息有效期
        protected ValuedEditor descriptionValuedEditor;
        protected ValuedTextBox miJingValuedTextBox;//米经
        protected ValuedTextBox diJingValuedTextBox;//地径
        protected HiddenField specificationHiddenField;
        protected HiddenField applicationSpecificationHiddenField;
        protected Literal editProductLiteral;
        protected Label avgPriceLtl;
        protected HtmlInputFile attachmentData;
        protected YuanlinImage yuanlinImage;
        protected IButton SaveButton;
        protected IButton BackButton;
        public CompanyFishery fishery = null;
        private string tradeType = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TradeType);
        private YuanlinUser user = HttpContext.Current.User as YuanlinUser;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetCompanyFisheryRequest(this));
        }
        protected override void OnLoad(EventArgs e)
        {
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
            AjaxManager.Register(this, "AjaxMethod");
        }

        private void Bind()
        {
            //种类
            AquacultureCategoryListRequest request = new AquacultureCategoryListRequest();
            request.CategoryType = (int)CategoryType.Fishery;
            EntityList categories = BusinessManager.GetAquacultureCategoryList(RequestHelper.BuildGetAquacultureCategoryListRequest(request));
            this.categoryRadioButtonList.DataSource = categories;
            this.categoryRadioButtonList.DataTextField = "Title";
            this.categoryRadioButtonList.DataValueField = "EntityId";
            this.categoryRadioButtonList.DataBind();

            //应用分类
            AquacultureAppCategoryListRequest request1 = new AquacultureAppCategoryListRequest();
            request1.CategoryType = (int)CategoryType.Fishery;
            EntityList applicationCategories = BusinessManager.GetAquacultureAppCategoryList(RequestHelper.BuildGetAquacultureAppCategoryListRequest(request1));
            applicationCategoryCheckBoxList.DataSource = applicationCategories;
            applicationCategoryCheckBoxList.DataValueField = "EntityId";
            applicationCategoryCheckBoxList.DataTextField = "Title";
            applicationCategoryCheckBoxList.DataBind();

            //种植方式
            EntityList aquacultureMethods = BusinessManager.GetAquacultureMethodList(RequestHelper.BuildGetAquacultureMethodListRequest());
            aquacultureMethodCheckBoxList.DataSource = aquacultureMethods;
            aquacultureMethodCheckBoxList.DataValueField = "EntityId";
            aquacultureMethodCheckBoxList.DataTextField = "Title";
            aquacultureMethodCheckBoxList.DataBind();

            //苗木属性
            EntityList aquacultureAttributes = BusinessManager.GetAquacultureAttributeList(RequestHelper.BuildGetAquacultureAttributeListRequest());
            aquacultureAttributeCheckBoxList.DataSource = aquacultureAttributes;
            aquacultureAttributeCheckBoxList.DataValueField = "EntityId";
            aquacultureAttributeCheckBoxList.DataTextField = "Title";
            aquacultureAttributeCheckBoxList.DataBind();

            //信息有效期
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("5天", "1"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("15天", "2"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("一个月", "3"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("三个月", "4"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("六个月", "5"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("九个月", "6"));
            this.expiredInfoRadioButtonList.Items.Add(new ListItem("十二个月", "7"));

            switch (tradeType)
            {
                case "0":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyFishery", "ControlPanelResources.xml");
                    }
                    break;
                case "2":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyFisheryQiuGou", "ControlPanelResources.xml");
                    }
                    break;
                case "1":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyFisheryJingPin", "ControlPanelResources.xml");
                    }
                    break;
                case "3":
                    {
                        editProductLiteral.Text = ResourceManager.GetString("System_Applications_Yuanlin_EditCompanyFisheryJiShou", "ControlPanelResources.xml");
                    }
                    break;
            }

            if (fishery != null)
            {
                this.titleValuedTextBox.Value = fishery.Title.Value;
                AquacultureListRequest productListRequest = new AquacultureListRequest();
                productListRequest.EqualTitle = fishery.Title.Value;
                productListRequest.CategoryType = (int)CategoryType.Fishery;
                EntityList products = BusinessManager.GetAquacultureList(RequestHelper.BuildGetAquacultureListRequest(productListRequest));
                if (products.Count > 0)
                {
                    aliasValuedTextBox.Value = (products[0] as Aquaculture).Alias.Value;
                }
                pinNameTitleValuedTextBox.Value = fishery.PinNameTitle.Value;
                categoryRadioButtonList.SelectedValue = fishery.CategoryId.Value.ToString();
                ListItem item = null;
                numberValuedTextBox.Value = fishery.Number.Value.ToString();
                priceValuedTextBox.Value = fishery.Price.Value.ToString("f2");
                miJingValuedTextBox.Value = fishery.MiJing.Value.ToString("f2");
                diJingValuedTextBox.Value = fishery.DiJing.Value.ToString("f2");
                yuanlinImage.Attachment = fishery; 
                foreach (string itemstrm in fishery.AquacultureMethod.Value.Split(','))
                {
                    item = this.aquacultureMethodCheckBoxList.Items.FindByValue(itemstrm);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
                foreach (string itemstrm in fishery.AquacultureAttribute.Value.Split(','))
                {
                    item = this.aquacultureAttributeCheckBoxList.Items.FindByValue(itemstrm);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
                registerTrademarkValuedTextBox.Value = fishery.RegisterTrademark.Value;
                this.productPriceFromFaceCheckBox.Value = fishery.ProductPriceFromFace.Value.ToString();
                expiredInfoRadioButtonList.SelectedValue = fishery.ExpiredInfo.Value.ToString();
                this.descriptionValuedEditor.Value = fishery.Body.Value;
                avgPriceLtl.Text = fishery.AvgPrice.Value.ToString();
                if (fishery.CategoryId.Value > -1)
                {
                    BindSpecification();
                }

                CompanyFisheryAndAppCategoryRelationListRequest request2 = new CompanyFisheryAndAppCategoryRelationListRequest();
                request2.FisheryId = fishery.EntityId.Value;
                EntityList relationList = BusinessManager.GetCompanyFisheryAndAppCategoryRelationList(RequestHelper.BuildGetCompanyFisheryAndAppCategoryRelationListRequest(request2));
                if (relationList.Count == 0)
                    return;

                foreach (CompanyFisheryAndAppCategoryRelation relation in relationList)
                {
                    item = this.applicationCategoryCheckBoxList.Items.FindByValue(relation.CategoryId.Value.ToString());
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        private void BindSpecification()
        {
            string returnValue = string.Empty;
            if (string.IsNullOrEmpty(fishery.GuiGeNames.Value) || string.IsNullOrEmpty(fishery.GuiGeValues.Value))
            {
                return;
            }
            string[] names = fishery.GuiGeNames.Value.Split(new string[] { "|" }, StringSplitOptions.None);
            string[] values = fishery.GuiGeValues.Value.Split(new string[] { "|" }, StringSplitOptions.None);
            string[] units = fishery.GuiGeUnits.Value.Split(new string[] { "|" }, StringSplitOptions.None);

            if (names.Length != values.Length)
            {
                return;
            }
            for (int i = 0; i < names.Length; i++)
            {
                returnValue += ";" + string.Format("{0}:{1}:{2}", names[i], units[i], values[i]);
            }
            if (returnValue.Length > 0)
            {
                returnValue = returnValue.Substring(1);
            }
            //绑定规格
            specificationHiddenField.Value = returnValue;

        }
       
        private void SetProductId(CompanyFishery companyFishery)
        {
            AquacultureListRequest request = new AquacultureListRequest();
            request.Title = companyFishery.Title.Value;
            EntityList products = BusinessManager.GetAquacultureList(RequestHelper.BuildGetAquacultureListRequest(request));
            if (products.TotalCount > 0)
            {
                companyFishery.FisheryId.Value = products[0].EntityId.Value;
            }
            else
            {
                companyFishery.FisheryId.Value = 0;
            }
        }

        public void BackButton_Click(object sender, EventArgs e)
        {
            PageRedirect();
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            if (fishery != null)
            {
                fishery.Title.Value = CensorWordManager.CensorWord(titleValuedTextBox.Value);
                fishery.PinNameTitle.Value = CensorWordManager.CensorWord(pinNameTitleValuedTextBox.Value);
                fishery.CategoryId.Value = Int32.Parse(categoryRadioButtonList.SelectedValue);
                fishery.Number.Value = this.numberValuedTextBox.Value.Length == 0 ? 0 : Convert.ToInt32(this.numberValuedTextBox.Value);
                fishery.Price.Value = priceValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(priceValuedTextBox.Text));
                fishery.MiJing.Value = miJingValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(miJingValuedTextBox.Text));
                fishery.DiJing.Value = diJingValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(diJingValuedTextBox.Text));
                fishery.AquacultureMethod.Value = "";
                foreach (ListItem item in this.aquacultureMethodCheckBoxList.Items)
                {
                    if (item.Selected)
                    {
                        fishery.AquacultureMethod.Value += "," + item.Value;
                    }
                }
                if (fishery.AquacultureMethod.Value.Length > 0)
                {
                    fishery.AquacultureMethod.Value = fishery.AquacultureMethod.Value.Substring(1);
                }
                foreach (ListItem item in this.aquacultureAttributeCheckBoxList.Items)
                {
                    if (item.Selected)
                    {
                        fishery.AquacultureAttribute.Value += "," + item.Value;
                    }
                }
                if (fishery.AquacultureAttribute.Value.Length > 0)
                {
                    fishery.AquacultureAttribute.Value = fishery.AquacultureAttribute.Value.Substring(1);
                }
                fishery.RegisterTrademark.Value = CensorWordManager.CensorWord(registerTrademarkValuedTextBox.Value);
                fishery.ProductPriceFromFace.Value = this.productPriceFromFaceCheckBox.Value.ToLower() == "false" ? 0 : 1;
                fishery.ExpiredInfo.Value = Int32.Parse(expiredInfoRadioButtonList.SelectedValue);
                fishery.Body.Value = CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);
                fishery.UpdateDate.Value = DateTime.Now;

                fishery.GreenNum.Value = user.CurrentGreenNumber;

                List<string> fieldNames = new List<string>();
                List<string> fieldValues = new List<string>();
                List<string> fieldUnits = new List<string>();
                if (specificationHiddenField.Value.Length > 0)
                {
                    string[] specifications = specificationHiddenField.Value.Split(';');
                    foreach (string item in specifications)
                    {
                        fieldNames.Add(item.Split(':')[0]);
                        fieldValues.Add(item.Split(':')[1]);
                        fieldUnits.Add(item.Split(':')[2]);
                    }
                }
                fishery.GuiGeNames.Value = string.Join("|", fieldNames.ToArray());
                fishery.GuiGeValues.Value = string.Join("|", fieldValues.ToArray());
                fishery.GuiGeUnits.Value = string.Join("|", fieldUnits.ToArray());

                SetProductId(fishery);

                BusinessManager.UpdateCompanyFishery(fishery);

                //创建与应用分类的关系
                CompanyFisheryAndAppCategoryRelation relation = new CompanyFisheryAndAppCategoryRelation();
                relation.EntityId.Value = 1;
                relation.FisheryId.Value = fishery.EntityId.Value;
                foreach (ListItem item in this.applicationCategoryCheckBoxList.Items)
                {
                    if (item.Selected)
                    {
                        relation.CategoryIds += "," + Globals.ChangeType<int>(item.Value);
                    }
                }
                if (!string.IsNullOrEmpty(relation.CategoryIds))
                {
                    relation.CategoryIds = relation.CategoryIds.Substring(1);
                    BusinessManager.UpdateCompanyFisheryAndAppCategoryRelation(relation);
                }
            }
            PageRedirect();
        }
        private void PageRedirect()
        {
            if (tradeType == "0")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryListUrl());
            }
            else if (tradeType == "2")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryQiuGouListUrl());
            }
            else if (tradeType == "1")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryJingPinListUrl());
            }
            else if (tradeType == "3")
            {
                Page.Response.Redirect(SiteUrls.Instance().GetCompanyFisheryJiShouListUrl());
            }
        }
        #region Ajax Method

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string ParentCategorySelectedChanged(string selectedValue)
        {
            if (string.IsNullOrEmpty(selectedValue))
            {
                return "";
            }

            return BindProductsAndSpecifications(int.Parse(selectedValue));
        }
        private string BindProductsAndSpecifications(int categoryID)
        {
            string returnValue = string.Empty;
            if (categoryID < 0)
            {
                return returnValue;
            }

            //绑定规格
            AquacultureGuiGeListRequest request = new AquacultureGuiGeListRequest();
            request.CategoryId = categoryID;
            EntityList guiges = BusinessManager.GetAquacultureGuiGeList(RequestHelper.BuildGetAquacultureGuiGeListRequest(request));
            if (guiges.Count > 0)
            {
                string format = "{0}:{1}";
                string str = string.Empty;
                foreach (AquacultureGuiGe guige in guiges)
                {
                    if (str != string.Empty)
                    {
                        str += ";";
                    }
                    str += string.Format(format, guige.Title, guige.Unit);
                }
                returnValue = str;
            }

            return returnValue;
        }

        #endregion

        #region IReplyConverter<CompanyFisheryReply,GetOperation> Members

        public void ConvertReply(CompanyFisheryReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                fishery = reply.Entity as CompanyFishery;

                if (!Page.IsPostBack)
                {
                    Bind();
                }
            }
        }

        #endregion
    }
}